package com.xbongbong.lfasr.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ChannelFileReader {
    private File file;
    private FileInputStream file_in;
    private ByteBuffer byte_buf;
    private byte[] array;
    private long file_len;
    private String file_ext;

    public ChannelFileReader(File file, int arraySize) throws IOException {
        this.file_in = new FileInputStream(file.getCanonicalPath());
        this.file_len = this.file_in.getChannel().size();
        this.byte_buf = ByteBuffer.allocate(arraySize);
        int i = file.getName().lastIndexOf(".");
        this.file_ext = file.getName().substring(i + 1);
    }

    public int read() throws IOException {
        FileChannel fileChannel = this.file_in.getChannel();
        int bytes = fileChannel.read(this.byte_buf);
        if (bytes != -1) {
            this.array = new byte[bytes];
            this.byte_buf.flip();
            this.byte_buf.get(this.array);
            this.byte_buf.clear();
            return bytes;
        } else {
            return -1;
        }
    }

    public void close() throws IOException {
        this.file_in.close();
        this.array = null;
    }

    public byte[] getArray() {
        return this.array;
    }

    public long getFileLength() {
        return this.file_len;
    }

    public File getFile() {
        return this.file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileExt() {
        return this.file_ext;
    }
}
